#include <stdio.h>
#include <stdlib.h>
#include "student.h"
#include "fileops.h"

#define FILENAME "./students.txt"
#define MAX_STUDENTS 100

Student students[MAX_STUDENTS];
int current_student_count = 0;

void saveToFile() {
    FILE *file = fopen(FILENAME, "w");
    if (!file) {
        printf("无法打开文件进行写入!\n");
        return;
    }

    for (int i = 0; i < current_student_count; i++) {
        fprintf(file, "%d,%s,%s,%d,%s,%s\n",
                students[i].id, students[i].name, students[i].gender,
                students[i].age, students[i].class, students[i].contact);
    }

    fclose(file);
    printf("数据已成功保存到 %s.\n", FILENAME);
}

void loadFromFile() {
    FILE *file = fopen(FILENAME, "r");
    if (!file) {
        printf("无法打开文件 %s 进行读取!\n", FILENAME);
        return;
    } else {
        printf("成功打开文件 %s.\n", FILENAME);
    }

    current_student_count = 0; // 重置学生数量
    char line[256]; // 假设每行最大256字符

    while (fgets(line, sizeof(line), file) != NULL) {
        int fieldsRead = sscanf(line, "%d,%49[^,],%9[^,],%d,%49[^,],%49[^\n]",
                                &students[current_student_count].id,
                                students[current_student_count].name,
                                students[current_student_count].gender,
                                &students[current_student_count].age,
                                students[current_student_count].class,
                                students[current_student_count].contact);

        if (fieldsRead == 6) { // 成功读取了6个字段
            current_student_count++;
        } else {
            printf("解析错误: %s\n", line);
        }

        if (current_student_count >= MAX_STUDENTS) {
            printf("警告: 达到最大学生数量限制!\n");
            break;
        }
    }

    fclose(file);
    printf("已从 %s 加载数据.\n", FILENAME);
}

